import { del, lists, po, put } from '../../api/info'
import { Table, Form, Input, Select, Button, Popconfirm, Space, Modal, Upload, message, Card, Tooltip } from 'antd';
import type { TableProps, UploadProps } from 'antd';
import { useEffect, useState } from 'react';
import { DeleteOutlined, EditOutlined, PlusOutlined, DownloadOutlined, PictureOutlined, EyeOutlined, DeleteOutlined as DeleteIcon } from '@ant-design/icons';
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import { initializeOSS, uploadToOSS } from '../../utils/oss';
import AA from '../../compages/aa/Index';

// 添加CSS动画样式
const styles = `
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  
  @keyframes pulse {
    0%, 100% { opacity: 0.5; transform: scale(1); }
    50% { opacity: 0.8; transform: scale(1.05); }
  }
  
  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  @keyframes slideIn {
    from {
      opacity: 0;
      transform: translateX(-20px);
    }
    to {
      opacity: 1;
      transform: translateX(0);
    }
  }
  
  .upload-container {
    animation: fadeInUp 0.6s ease-out;
  }
  
  .image-preview {
    animation: slideIn 0.4s ease-out;
  }
  
  .upload-button {
    position: relative;
    overflow: hidden;
  }
  
  .upload-button::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.4), transparent);
    transition: left 0.5s;
  }
  
  .upload-button:hover::before {
    left: 100%;
  }
`;

// 注入样式
if (typeof document !== 'undefined') {
  const styleSheet = document.createElement('style');
  styleSheet.textContent = styles;
  document.head.appendChild(styleSheet);
}

// 定义数据类型
interface ShopDataType {
  id: string;
  shopName: string;
  shopAddress: string;
  shopType: string;
  shopScore: number;
  shopSellCount: number;
  shopTel: string;
  shopDescription: string;
  shopImage: string;
}

interface FormDataType {
  searchValue: string;
  type: string;
  minScore: string;
  maxScore: string;
}

function Index() {
  // 检测是否是管理员
  const [show, setShow] = useState(false)
  const name = localStorage.getItem('name')
  useEffect(() => {
    if (name === 'admin') {
      setShow(true)
    } else {
      setShow(false)
    }
  }, [name])
  // 数据
  const [list, setList] = useState<ShopDataType[]>([])
  const [pageCode, setPage] = useState(1)
  const [pageSize, setSize] = useState(10)
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [formData, setFromData] = useState<FormDataType>({
    searchValue: '',
    type: '',
    minScore: '',
    maxScore: ''
  })
  const get = async () => {
    setLoading(true)
    try {
    const res = await lists('/list', { pageCode, pageSize, ...formData })
      console.log('API response:', res); // 添加调试信息
    const { code, data } = res.data
    if (code === 10000) {
        console.log('Data received:', data); // 添加调试信息
        console.log('Shop images in data:', data.data?.map((item: ShopDataType) => ({ id: item.id, shopImage: item.shopImage }))); // 添加调试信息
      setTotal(data.totalCount)
      setList(data.data)
      setLoading(false)
      } else {
        console.error('API returned error code:', code); // 添加调试信息
      setLoading(false)
    }
    } catch (error) {
      console.error('Failed to fetch data:', error); // 添加调试信息
      setLoading(false)
    }
  }
  useEffect(() => {
    get()
  }, [pageCode, pageSize, formData])

  useEffect(() => {
    initializeOSS();
  }, []);

  // 数据--------------------------------------------------
  const columns: TableProps<ShopDataType>['columns'] = [
    {
      title: '店铺ID',
      dataIndex: 'id',
      key: 'id',
      render: (text) => <span>{text}</span>,
    },
    {
      title: '店铺名称',
      dataIndex: 'shopName',
      key: 'shopName',
      render: (text) => <span>{text}</span>,
    },
    {
      title: '店铺地址',
      dataIndex: 'shopAddress',
      key: 'shopAddress',
      render: (text) => <span>{text}</span>,
    },
    {
      title: '店铺类型',
      dataIndex: 'shopType',
      key: 'shopType',
      render: (text) => (
        <span>{text}</span>
      ),
    },
    {
      title: '店铺评分',
      dataIndex: 'shopScore',
      key: 'shopScore',
      render: (score) => (
        <div>
          <span>{score}</span>
          {/* <span style={{ color: score < 3 ? 'red' : score < 4 ? 'orange' : 'green' }}>
            {score >= 4 ? '优秀' : score >= 3 ? '一般' : '较差'}
          </span> */}
        </div>
      ),
    },
    {
      title: '销量',
      dataIndex: 'shopSellCount',
      key: 'shopSellCount',
      render: (count) => <span>{count} 件</span>,
    },
    {
      title: '联系电话',
      dataIndex: 'shopTel',
      key: 'shopTel',
      render: (text) => <span>{text}</span>,
    },
    {
      title: '店铺描述',
      dataIndex: 'shopDescription',
      key: 'shopDescription',
      render: (text) => <span title={text}>{text}</span>, // 长文本添加悬浮提示
    },
    {
      title: '店铺图片',
      dataIndex: 'shopImage',
      key: 'shopImage',
      render: (imageUrl) => (
        <div style={{ position: 'relative', width: 80, height: 80 }}>
          {imageUrl ? (
            <>
        <img
          src={imageUrl}
          alt="店铺图片"
                style={{ 
                  width: 80, 
                  height: 80, 
                  objectFit: 'cover', 
                  borderRadius: 4,
                  border: '1px solid #e8e8e8'
                }}
                onError={(e) => {
                  // 图片加载失败时隐藏图片
                  const target = e.target as HTMLImageElement;
                  target.style.display = 'none';
                }}
              />
              {/* 图片加载失败时的占位符 */}
              <div
                style={{
                  width: 80,
                  height: 80,
                  borderRadius: 4,
                  border: '1px solid #e8e8e8',
                  background: '#f5f5f5',
                  display: 'none',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#999',
                  fontSize: '12px',
                  textAlign: 'center',
                  lineHeight: '1.2'
                }}
              >
                图片加载失败
              </div>
            </>
          ) : (
            <div
              style={{
                width: 80,
                height: 80,
                borderRadius: 4,
                border: '1px dashed #d9d9d9',
                background: '#fafafa',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: '#999',
                fontSize: '12px',
                textAlign: 'center',
                lineHeight: '1.2'
              }}
            >
              暂无图片
            </div>
          )}
        </div>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          {show === true ? <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <Button
              type="link"
              icon={<EditOutlined />}
              onClick={() => showModal(record)}
            >
              编辑
            </Button>
            <Popconfirm
              title="提示"
              description="确认删除吗?"
              onConfirm={() => confirm(record.id)}
              okText="Yes"
              cancelText="No"
            >
              <Button
                type="link"
                danger
                icon={<DeleteOutlined />}
              >
                删除
              </Button>
            </Popconfirm>

          </div> : <div>
            <Button color="primary" variant="solid" onClick={() => showModal(record)}>
              编辑
            </Button>
          </div>
          }

        </Space>
      ),
    },
  ];
  // 分页----------------------------------------------------
  const chang = (page: number, size: number) => {
    setPage(page)
    setSize(size)
  }
  // 搜索----------------------------------------------------
  const [form] = Form.useForm()
  const onFinish = (values: FormDataType) => {
    setFromData(values)
  };
  const out = () => {
    form.resetFields()
    setFromData({
      searchValue: '',
      type: '',
      minScore: '',
      maxScore: ''
    })
  }
  // 批量删除------------------------------------------------------
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  // 删除-----------------------------------------------------
  const confirm = async (id: string) => {
    console.log('11', id);
    await del('/list', { id: id })
    get()
  };
  // 编辑+新增
  const [forms] = Form.useForm()
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [text, setText] = useState<'bj' | 'xz' | undefined>()
  // 编辑 ----------------------------------------------------
  const showModal = (val: ShopDataType) => {
    setText('bj')
    forms.setFieldsValue(val)
    // 设置图片URL用于预览
    setImageUrl(val.shopImage || '')
    // 如果有现有图片，获取图片信息
    if (val.shopImage) {
      setImageLoading(true); // 开始加载
      fetch(val.shopImage)
        .then(response => response.blob())
        .then(blob => {
          const file = new File([blob], 'existing-image.jpg', { type: blob.type });
          getImageInfo(file).then(info => {
            setImageInfo(info);
            setImageLoading(false); // 加载完成
          });
        })
        .catch(() => {
          // 如果无法获取图片信息，设置默认信息
          setImageInfo({ width: 0, height: 0, size: '未知' });
          setImageLoading(false); // 加载完成
        });
    }
    setIsModalOpen(true);
  };
  // 判断编辑还是新增
  const handleOk = async () => {
    const formData = forms.getFieldsValue();
    console.log('Form data being submitted:', formData); // 添加调试信息
    console.log('Image URL in form:', formData.shopImage); // 添加调试信息
    
    try {
    if (text === 'bj') {
        console.log('Editing existing item...'); // 添加调试信息
        const response = await po('/list', formData);
        console.log('Edit response:', response); // 添加调试信息
    }
    else {
        console.log('Adding new item...'); // 添加调试信息
        const response = await put('/list', formData);
        console.log('Add response:', response); // 添加调试信息
    }
      
    forms.resetFields()
      setImageUrl('') // 清空图片URL
      setImageInfo(null) // 清空图片信息
    get()
    setIsModalOpen(false);
    } catch (error) {
      console.error('API call failed:', error); // 添加调试信息
      message.error('操作失败，请稍后重试');
    }
  };
  const handleCancel = () => {
    setIsModalOpen(false);
    setImageUrl('') // 清空图片URL
    setImageInfo(null) // 清空图片信息
  };
  // 新增 ----------------------------------------------------
  const xz = () => {
    setText('xz')
    setImageUrl('') // 清空图片URL
    setImageInfo(null) // 清空图片信息
    setIsModalOpen(true);
  }
  // 图片上传状态
  const [imageUrl, setImageUrl] = useState<string>('');
  const [uploading, setUploading] = useState(false);
  const [imageInfo, setImageInfo] = useState<{ width: number; height: number; size: string } | null>(null);
  const [imageLoading, setImageLoading] = useState(false);
  const [dragOver, setDragOver] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);

  // 优化的图片压缩功能
  const compressImage = (file: File, maxWidth: number = 800, quality: number = 0.8): Promise<File> => {
    return new Promise((resolve, reject) => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      const img = new Image();
      
      img.onload = () => {
        try {
          const { width, height } = img;
          let newWidth = width;
          let newHeight = height;
          
          // 如果图片太大，按比例缩小
          if (width > maxWidth) {
            newWidth = maxWidth;
            newHeight = (height * maxWidth) / width;
          }
          
          // 设置canvas尺寸
          canvas.width = newWidth;
          canvas.height = newHeight;
          
          // 绘制图片到canvas
          ctx?.drawImage(img, 0, 0, newWidth, newHeight);
          
          // 转换为blob
          canvas.toBlob((blob) => {
            if (blob) {
              const compressedFile = new File([blob], file.name, {
                type: file.type,
                lastModified: Date.now(),
              });
              console.log('压缩完成:', {
                原始大小: file.size,
                压缩后大小: compressedFile.size,
                压缩比例: Math.round((1 - compressedFile.size / file.size) * 100) + '%'
              });
              resolve(compressedFile);
            } else {
              reject(new Error('图片压缩失败'));
            }
          }, file.type, quality);
        } catch (error) {
          reject(error);
        }
      };
      
      img.onerror = () => {
        reject(new Error('图片加载失败'));
      };
      
      img.src = URL.createObjectURL(file);
    });
  };

  // 获取图片信息
  const getImageInfo = (file: File): Promise<{ width: number; height: number; size: string }> => {
    return new Promise((resolve) => {
      const img = new Image();
      img.onload = () => {
        const size = (file.size / 1024 / 1024).toFixed(2);
        resolve({
          width: img.width,
          height: img.height,
          size: `${size}MB`
        });
      };
      img.onerror = () => {
        resolve({
          width: 0,
          height: 0,
          size: '未知'
        });
      };
      img.src = URL.createObjectURL(file);
    });
  };

  // 优化的图片上传配置 - 完全本地化方案
  const uploadProps: UploadProps = {
    name: 'file',
    action: undefined,
    headers: {
      authorization: 'authorization-text',
    },
    accept: 'image/*',
    maxCount: 1,
    listType: 'picture-card',
    showUploadList: false,
    customRequest: async ({ file, onSuccess, onError }) => {
      try {
        setUploadProgress(10);
        let uploadFile = file as File;
        if (uploadFile.size > 1 * 1024 * 1024) {
          setUploadProgress(30);
          uploadFile = await compressImage(uploadFile, 800, 0.7);
        }
        setUploadProgress(50);
        // 上传到OSS并拿到URL
        const ossUrl = await uploadToOSS(uploadFile);
        setUploadProgress(80);
        // 存到表单字段，后端保存后列表即可显示
        forms.setFieldsValue({ shopImage: ossUrl });
        setImageUrl(ossUrl);
        setUploadProgress(100);
        message.success('图片上传成功（OSS）');
        onSuccess?.(ossUrl);
      } catch (err) {
        setUploadProgress(0);
        message.error('图片上传失败');
        onError?.(err);
      }
    },
    beforeUpload: async (file) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        message.error('只能上传图片文件！');
        return false;
      }
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        message.error('图片大小不能超过10MB！');
        return false;
      }
      return true;
    },
    onRemove: () => {
      setImageUrl('');
      setImageInfo(null);
      forms.setFieldsValue({ shopImage: '' });
      message.info('已移除图片');
      return true;
    },
  };

  // 自定义上传按钮
  const uploadButton = (
    <div
      className="upload-container"
      style={{
        width: '120px',
        height: '120px',
        border: '2px dashed',
        borderColor: dragOver ? '#1890ff' : '#d9d9d9',
        borderRadius: '12px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        cursor: 'pointer',
        transition: 'all 0.3s ease',
        background: dragOver ? 'rgba(24, 144, 255, 0.02)' : '#fafafa',
        position: 'relative',
        overflow: 'hidden',
        padding: '12px',
        minHeight: 'auto',
      }}
      onDragOver={(e) => {
        e.preventDefault();
        setDragOver(true);
      }}
      onDragLeave={(e) => {
        e.preventDefault();
        setDragOver(false);
      }}
      onDrop={(e) => {
        e.preventDefault();
        setDragOver(false);
        // 处理拖拽文件
        const files = Array.from(e.dataTransfer.files);
        if (files.length > 0) {
          const file = files[0];
          if (file.type.startsWith('image/')) {
            // 触发文件上传
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = 'image/*';
            input.files = e.dataTransfer.files;
            input.dispatchEvent(new Event('change', { bubbles: true }));
          } else {
            message.error('只能上传图片文件！');
          }
        }
      }}
    >
      {/* 背景装饰 */}
      <div style={{
        position: 'absolute',
        top: '-50%',
        left: '-50%',
        width: '200%',
        height: '200%',
        background: dragOver 
          ? 'radial-gradient(circle, rgba(24, 144, 255, 0.1) 0%, transparent 70%)'
          : 'radial-gradient(circle, rgba(0, 0, 0, 0.02) 0%, transparent 70%)',
        animation: dragOver ? 'pulse 2s infinite' : 'none',
        zIndex: 0,
      }} />
      
      <div style={{ position: 'relative', zIndex: 1 }}>
        {uploading ? (
          <div style={{ width: '100%' }}>
            <div style={{ 
              fontSize: '14px', 
              marginBottom: '8px', 
              color: '#1890ff',
              fontWeight: 500,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: '6px'
            }}>
              <div style={{
                width: '12px',
                height: '12px',
                border: '2px solid #1890ff',
                borderTop: '2px solid transparent',
                borderRadius: '50%',
                animation: 'spin 1s linear infinite'
              }} />
              上传中...
            </div>
            <AA progress={uploadProgress} />
            <div style={{ fontSize: '11px', color: '#666', marginTop: '6px' }}>
                {uploadProgress < 30 ? '正在处理图片...' : 
                 uploadProgress < 70 ? '正在上传...' : 
                 uploadProgress < 90 ? '即将完成...' : '完成中...'}
              </div>
          </div>
        ) : (
          <div>
            <div style={{
              width: '48px',
              height: '48px',
              borderRadius: '50%',
              background: dragOver 
                ? 'linear-gradient(135deg, #1890ff 0%, #40a9ff 100%)'
                : 'linear-gradient(135deg, #f0f0f0 0%, #e6e6e6 100%)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              margin: '0 auto 8px',
              transition: 'all 0.3s ease',
              boxShadow: dragOver 
                ? '0 2px 8px rgba(24, 144, 255, 0.3)'
                : '0 1px 4px rgba(0, 0, 0, 0.1)',
            }}>
              <PictureOutlined style={{ 
                fontSize: '20px', 
                color: dragOver ? 'white' : '#999',
                transition: 'all 0.3s ease'
              }} />
            </div>
            <div style={{ 
              fontSize: '12px', 
              color: dragOver ? '#1890ff' : '#333', 
              marginBottom: '4px',
              fontWeight: 500,
              transition: 'all 0.3s ease'
            }}>
              {dragOver ? '释放文件以上传' : '点击或拖拽上传'}
            </div>
            <div style={{ 
              fontSize: '10px', 
              color: '#666', 
              marginBottom: '4px',
              lineHeight: '1.3'
            }}>
              支持 JPG、PNG、GIF 格式
            </div>
            <div style={{ 
              fontSize: '9px', 
              color: '#999',
              lineHeight: '1.3'
            }}>
              最大 10MB • 建议 800×600+
            </div>
          </div>
        )}
      </div>
    </div>
  );

  // 图片预览组件
  const ImagePreview = ({ url, onRemove }: { url: string; onRemove: () => void }) => (
    <div 
      className="image-preview"
      style={{ 
        position: 'relative', 
        display: 'inline-block',
        borderRadius: '8px',
        overflow: 'hidden',
        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
        transition: 'all 0.3s ease',
      }}
      onMouseEnter={(e) => {
        e.currentTarget.style.transform = 'scale(1.02)';
        e.currentTarget.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.transform = 'scale(1)';
        e.currentTarget.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.1)';
      }}
    >
      <img
        src={url}
        alt="店铺图片"
        style={{ 
          width: '80px', 
          height: '80px', 
          objectFit: 'cover', 
          display: 'block',
          transition: 'all 0.3s ease',
        }}
      />
      <div style={{
        position: 'absolute',
        top: '0',
        left: '0',
        right: '0',
        bottom: '0',
        background: 'linear-gradient(135deg, rgba(0,0,0,0.7) 0%, rgba(0,0,0,0.4) 100%)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        opacity: 0,
        transition: 'all 0.3s ease',
        gap: '6px',
        backdropFilter: 'blur(2px)',
      }}
      onMouseEnter={(e) => e.currentTarget.style.opacity = '1'}
      onMouseLeave={(e) => e.currentTarget.style.opacity = '0'}
      >
        <Tooltip title="预览图片">
          <Button 
            type="text" 
            icon={<EyeOutlined />} 
            style={{ 
              color: 'white',
              background: 'rgba(255, 255, 255, 0.2)',
              border: '1px solid rgba(255, 255, 255, 0.3)',
              borderRadius: '6px',
              width: '28px',
              height: '28px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              transition: 'all 0.2s ease',
              fontSize: '12px',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = 'rgba(255, 255, 255, 0.3)';
              e.currentTarget.style.transform = 'scale(1.1)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'rgba(255, 255, 255, 0.2)';
              e.currentTarget.style.transform = 'scale(1)';
            }}
            onClick={() => window.open(url)}
          />
        </Tooltip>
        <Tooltip title="删除图片">
          <Button 
            type="text" 
            icon={<DeleteIcon />} 
            style={{ 
              color: 'white',
              background: 'rgba(255, 77, 79, 0.8)',
              border: '1px solid rgba(255, 77, 79, 0.3)',
              borderRadius: '6px',
              width: '28px',
              height: '28px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              transition: 'all 0.2s ease',
              fontSize: '12px',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = 'rgba(255, 77, 79, 1)';
              e.currentTarget.style.transform = 'scale(1.1)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'rgba(255, 77, 79, 0.8)';
              e.currentTarget.style.transform = 'scale(1)';
            }}
            onClick={onRemove}
          />
        </Tooltip>
      </div>
    </div>
  );

  // 导出Excel功能
  const exportToExcel = () => {
    if (list.length === 0) {
      message.warning('没有数据可导出');
      return;
    }

    // 准备导出数据
    const exportData = list.map((item: ShopDataType) => ({
      '店铺ID': item.id,
      '店铺名称': item.shopName,
      '店铺地址': item.shopAddress,
      '店铺类型': item.shopType,
      '店铺评分': item.shopScore,
      '销量': item.shopSellCount,
      '联系电话': item.shopTel,
      '店铺描述': item.shopDescription,
      '店铺图片': item.shopImage
    }));

    // 创建工作簿
    const ws = XLSX.utils.json_to_sheet(exportData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '店铺列表');

    // 设置列宽
    const colWidths = [
      { wch: 10 }, // 店铺ID
      { wch: 15 }, // 店铺名称
      { wch: 25 }, // 店铺地址
      { wch: 10 }, // 店铺类型
      { wch: 10 }, // 店铺评分
      { wch: 10 }, // 销量
      { wch: 15 }, // 联系电话
      { wch: 30 }, // 店铺描述
      { wch: 50 }, // 店铺图片
    ];
    ws['!cols'] = colWidths;

    // 生成Excel文件
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    
    // 下载文件
    const fileName = `店铺列表_${new Date().toISOString().slice(0, 10)}.xlsx`;
    saveAs(blob, fileName);
    
    message.success('Excel文件导出成功！');
  };

  // 本地图片存储管理
  const saveImageToLocalStorage = (imageData: string, fileName: string) => {
    try {
      // 生成唯一ID
      const imageId = `img_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      
      // 保存到localStorage
      const imageInfo = {
        id: imageId,
        data: imageData,
        fileName: fileName,
        timestamp: Date.now(),
        size: imageData.length
      };
      
      localStorage.setItem(imageId, JSON.stringify(imageInfo));
      console.log('图片已保存到本地存储:', imageId, '大小:', imageData.length);
      
      return imageId;
    } catch (error) {
      console.error('保存图片到本地存储失败:', error);
      return null;
      }
  };

  const getImageFromLocalStorage = (imageId: string) => {
    try {
      const imageInfo = localStorage.getItem(imageId);
      if (imageInfo) {
        const parsed = JSON.parse(imageInfo);
        return parsed.data;
      }
      return null;
    } catch (error) {
      console.error('从本地存储获取图片失败:', error);
      return null;
    }
  };

  const removeImageFromLocalStorage = (imageId: string) => {
    try {
      localStorage.removeItem(imageId);
      console.log('图片已从本地存储移除:', imageId);
    } catch (error) {
      console.error('从本地存储移除图片失败:', error);
    }
  };

  return (
    <div>
      {/* 搜索 */}
      <Card style={{ marginBottom: '16px' }}>
        <Space>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={xz}
          >
            添加用户
          </Button>
          {/* 批量删除 */}
          {show === true ? <Popconfirm
            title="Delete the task"
            description="Are you sure to delete this task?"
            onConfirm={() => confirm(selectedRowKeys.join(','))}
            okText="Yes"
            cancelText="No"
          >
            <Button icon={<DeleteOutlined />}>批量删除</Button>
          </Popconfirm> : <div></div>}
          <Form
            form={form}
            name="basic"
            style={{ maxWidth: 2000 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            layout='inline'
          >

            <Form.Item
              // label="搜索"
              name="searchValue"
            >
              <Input placeholder="搜索" />
            </Form.Item>
            <Form.Item
              // label="类型"
              name="type"
            >
              {/* ["生鲜", "水果", "冷饮", "甜品", "鲜花"] */}
              <Select
                allowClear
                defaultValue="类型"
                style={{ width: 120 }}
                // onChange={handleChange}
                options={[
                  { value: '生鲜', label: '生鲜' },
                  { value: '水果', label: '水果' },
                  { value: '冷饮', label: '冷饮' },
                  { value: '甜品', label: '甜品' },
                  { value: '鲜花', label: '鲜花' },
                ]}
              />
            </Form.Item>
            <Form.Item>
              <Button color="primary" variant="solid" htmlType="submit">
                搜索
              </Button>
            </Form.Item>
            <Form.Item>
              <Button onClick={out}>重置</Button>
            </Form.Item>
          </Form>
          <Button 
            color="primary" 
            variant="solid" 
            icon={<DownloadOutlined />}
            onClick={exportToExcel}
            loading={loading}
          >
            导出Excel
          </Button>
        </Space>
      </Card>

      {/* 编辑新增 */}
      <Modal
        title={text === 'bj' ? '编辑' : '新增'}
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={forms}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          autoComplete="off"
        >
          {text === 'bj' && <Form.Item
            label="ID"
            name="id"
          >
            <Input disabled />
          </Form.Item>}
          <Form.Item
            label="店铺名称"
            name="shopName"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="店铺地址"
            name="shopAddress"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="店铺类型"
            name="shopType"
          >
            <Select
              allowClear
              defaultValue=""
              style={{ width: 120 }}
              options={[
                { value: '生鲜', label: '生鲜' },
                { value: '水果', label: '水果' },
                { value: '冷饮', label: '冷饮' },
                { value: '甜品', label: '甜品' },
                { value: '鲜花', label: '鲜花' },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="店铺评分"
            name="shopScore"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="销量"
            name="shopSellCount"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="联系电话"
            name="shopTel"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="店铺描述"
            name="shopDescription"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="店铺图片"
            name="shopImage"
            rules={[
              { required: true, message: '请上传店铺图片！' }
            ]}
            extra={
              <div style={{
                fontSize: '11px',
                color: '#666',
                marginTop: '4px',
                padding: '8px 12px',
                background: 'linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)',
                borderRadius: '8px',
                border: '1px solid #e9ecef'
              }}>
                <div style={{ fontWeight: 500, marginBottom: '2px', color: '#333', fontSize: '12px' }}>
                  📸 图片上传建议
                </div>
                <div style={{ fontSize: '10px', lineHeight: '1.3' }}>• 建议上传清晰、美观的店铺图片</div>
                <div style={{ fontSize: '10px', lineHeight: '1.3' }}>• 尺寸建议：800×600 像素或更大</div>
                <div style={{ fontSize: '10px', lineHeight: '1.3' }}>• 文件大小：不超过 10MB</div>
                <div style={{ fontSize: '10px', lineHeight: '1.3' }}>• 支持格式：JPG、PNG、GIF</div>
              </div>
            }
          >
            <div>
              <Upload {...uploadProps}>
                {imageUrl ? (
                  <ImagePreview 
                    url={imageUrl} 
                    onRemove={() => {
                      setImageUrl('');
                      setImageInfo(null);
                      forms.setFieldsValue({ shopImage: '' });
                    }}
                  />
                ) : (
                  uploadButton
                )}
            </Upload>
              {imageUrl && imageInfo && (
                <div 
                  className="image-preview"
                  style={{ 
                    marginTop: '8px', 
                    padding: '12px', 
                    background: 'linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)',
                    borderRadius: '8px', 
                    fontSize: '12px', 
                    color: '#333',
                    border: '1px solid #e9ecef',
                    boxShadow: '0 1px 4px rgba(0, 0, 0, 0.04)',
                    transition: 'all 0.3s ease',
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.transform = 'translateY(-1px)';
                    e.currentTarget.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.08)';
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.transform = 'translateY(0)';
                    e.currentTarget.style.boxShadow = '0 1px 4px rgba(0, 0, 0, 0.04)';
                  }}
                >
                  {imageLoading ? (
                    <div style={{ 
                      display: 'flex', 
                      alignItems: 'center', 
                      gap: '6px',
                      color: '#666',
                      fontSize: '11px'
                    }}>
                      <div style={{
                        width: '10px',
                        height: '10px',
                        border: '2px solid #1890ff',
                        borderTop: '2px solid transparent',
                        borderRadius: '50%',
                        animation: 'spin 1s linear infinite'
                      }} />
                      正在加载图片信息...
                    </div>
                  ) : (
                    <>
                      <div style={{ 
                        display: 'flex', 
                        alignItems: 'center', 
                        gap: '6px',
                        marginBottom: '8px',
                        fontWeight: 500,
                        fontSize: '12px'
                      }}>
                        <span style={{ fontSize: '14px' }}>📊</span>
                        图片信息
                      </div>
                      <div style={{ 
                        display: 'grid', 
                        gridTemplateColumns: '1fr 1fr', 
                        gap: '8px',
                        marginBottom: '8px'
                      }}>
                        <div style={{ 
                          padding: '8px', 
                          background: 'white', 
                          borderRadius: '6px',
                          textAlign: 'center',
                          border: '1px solid #e9ecef',
                          transition: 'all 0.2s ease',
                          cursor: 'pointer'
                        }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.transform = 'scale(1.02)';
                          e.currentTarget.style.boxShadow = '0 1px 4px rgba(0, 0, 0, 0.1)';
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.transform = 'scale(1)';
                          e.currentTarget.style.boxShadow = 'none';
                        }}
                        >
                          <div style={{ fontSize: '10px', color: '#666', marginBottom: '2px' }}>尺寸</div>
                          <div style={{ fontWeight: 600, fontSize: '12px' }}>{imageInfo.width} × {imageInfo.height}</div>
                        </div>
                        <div style={{ 
                          padding: '8px', 
                          background: 'white', 
                          borderRadius: '6px',
                          textAlign: 'center',
                          border: '1px solid #e9ecef',
                          transition: 'all 0.2s ease',
                          cursor: 'pointer'
                        }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.transform = 'scale(1.02)';
                          e.currentTarget.style.boxShadow = '0 1px 4px rgba(0, 0, 0, 0.1)';
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.transform = 'scale(1)';
                          e.currentTarget.style.boxShadow = 'none';
                        }}
                        >
                          <div style={{ fontSize: '10px', color: '#666', marginBottom: '2px' }}>大小</div>
                          <div style={{ fontWeight: 600, fontSize: '12px' }}>{imageInfo.size}</div>
                        </div>
                      </div>
                      <div style={{ 
                        display: 'flex', 
                        alignItems: 'center', 
                        gap: '6px',
                        marginBottom: '8px',
                        padding: '6px 8px',
                        background: 'rgba(24, 144, 255, 0.05)',
                        borderRadius: '6px',
                        border: '1px solid rgba(24, 144, 255, 0.1)',
                        fontSize: '11px'
                      }}>
                        <span style={{ fontSize: '12px' }}>👁️</span>
                        <a 
                          href={imageUrl} 
                          target="_blank" 
                          rel="noopener noreferrer"
                          style={{
                            color: '#1890ff',
                            textDecoration: 'none',
                            fontWeight: 500,
                            transition: 'all 0.2s ease',
                            fontSize: '11px'
                          }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.textDecoration = 'underline';
                            e.currentTarget.style.color = '#40a9ff';
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.textDecoration = 'none';
                            e.currentTarget.style.color = '#1890ff';
                          }}
                        >
                          查看原图
                        </a>
                      </div>
                      {imageInfo.width < 800 || imageInfo.height < 600 ? (
                        <div style={{ 
                          display: 'flex', 
                          alignItems: 'center', 
                          gap: '6px',
                          padding: '8px 12px',
                          background: 'rgba(250, 173, 20, 0.1)',
                          borderRadius: '6px',
                          border: '1px solid rgba(250, 173, 20, 0.3)',
                          color: '#d48806',
                          animation: 'pulse 2s infinite',
                          fontSize: '11px'
                        }}>
                          <span style={{ fontSize: '12px' }}>⚠️</span>
                          <span>建议上传更大尺寸的图片</span>
                        </div>
                      ) : (
                        <div style={{ 
                          display: 'flex', 
                          alignItems: 'center', 
                          gap: '6px',
                          padding: '8px 12px',
                          background: 'rgba(82, 196, 26, 0.1)',
                          borderRadius: '6px',
                          border: '1px solid rgba(82, 196, 26, 0.3)',
                          color: '#52c41a',
                          fontSize: '11px'
                        }}>
                          <span style={{ fontSize: '12px' }}>✅</span>
                          <span>图片尺寸符合要求</span>
                        </div>
                      )}
                    </>
                  )}
                </div>
              )}
            </div>
          </Form.Item>
        </Form>
      </Modal>

      {/* 分页 */}
      <Table<ShopDataType> rowKey='id' columns={columns} dataSource={list}
        rowSelection={{
          onChange(selectedRowKeys) {
            setSelectedRowKeys(selectedRowKeys as string[])
          }
        }}
        // loading加载 
        loading={loading}
        pagination={{
          total: total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `Total ${total} items`,
          onChange: chang
        }}
      />
    </div>
  )
}

export default Index
